﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using LibraryMusicStore;
using System.Data.Linq;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraEditors.ViewInfo;

namespace AppMusicStore
{
    public partial class frmOrder : DevExpress.XtraEditors.XtraForm
    {
        IRepository<Order> orderRepository;

        public frmOrder()
        {
            InitializeComponent();
        }

        private void frmReceipt_Load(object sender, EventArgs e)
        {
            try
            {
                orderRepository = new Repository<Order>();
                ReceiveData();
            }
            catch (Exception ex)
            {
                Common.ShowErrorBox(ex.Message);
            }
        }

        private void ReceiveData()
        {
            bindingSource1.DataSource = orderRepository.GetAll()
                .OrderByDescending(o => o.OrderId);
                //Common.GetReceipts(db);
        }

        private void Editor_Click(object sender, EventArgs e)
        {
            try
            {
                frmOrderEditor frm = new frmOrderEditor();
                frm.OrderRepository = this.orderRepository;

                if (sender.GetType().Name == "SimpleButton")
                    frm.Text = "Thêm đơn hàng";
                else
                {
                    if (gridView1.GetFocusedRowCellValue("OrderId") == null)
                        return;
                    frm.Text = "Sửa đơn hàng";
                    frm.id = Convert.ToInt32(gridView1.GetFocusedRowCellValue("OrderId"));
                }

                if (frm.ShowDialog(this) == DialogResult.OK)
                {
                    orderRepository = new Repository<Order>();
                    ReceiveData();
                }
                frm.Dispose();
            }
            catch (Exception ex)
            {
                Common.ShowErrorBox(ex.Message);
            }
        }

        private void btnDelete_Click()
        {
            try
            {
                DialogResult rs;
                Order order;

                if (gridView1.SelectedRowsCount > 1)
                {
                    int[] iRows = gridView1.GetSelectedRows();

                    rs = Common.ShowQuestionBox("Xóa các đơn đã chọn?", "okcancel");

                    if (rs == DialogResult.OK)
                    {
                        foreach (var item in iRows)
                        {
                            order = orderRepository.GetById(
                                Convert.ToInt32(gridView1
                                .GetRowCellValue(item, "OrderId")));

                            orderRepository.DeleteOnSubmit(order);
                        }

                        orderRepository.SubmitChanges();

                        gridView1.DeleteSelectedRows();
                        gridControl1.Update();
                    }
                    return;
                }

                if (gridView1.GetFocusedRowCellValue("OrderId") == null)
                    return;

                order = orderRepository.GetById(
                    Convert.ToInt32(gridView1
                    .GetFocusedRowCellValue("OrderId")));

                rs = Common.ShowQuestionBox("Xóa đơn " + order
                    .OrderId + " ?", "okcancel");

                if (rs == DialogResult.OK)
                {
                    orderRepository.DeleteOnSubmit(order);
                    orderRepository.SubmitChanges();
                    gridView1.DeleteSelectedRows();
                    gridControl1.Update();
                    MessageBox.Show("Đã xóa", "Thông báo", MessageBoxButtons.OK);
                }
            }
            catch (Exception ex)
            {
                Common.ShowErrorBox(ex.Message);
            }

            //InitGridProducts();
        }

        #region "Context menu item"
        private void InsertToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //this.Editor_Click(this.btnInsert, new EventArgs());
            btnInsert.PerformClick();
        }

        private void EditToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Editor_Click(this.repositoryItemButtonEdit, new EventArgs());
        }


        private void DeleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnDelete_Click();
        }
        #endregion

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            if (gridView1.GetFocusedRowCellValue("ReceiptId") == null)
                ChangeVisibleToolTip(false);
            else
                ChangeVisibleToolTip(true);
        }

        private void ChangeVisibleToolTip(bool p)
        {
            EditToolStripMenuItem.Visible = p;
            DeleteToolStripMenuItem.Visible = p;
        }

        private void gridView1_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                if (Control.ModifierKeys != Keys.None) return;

                var view = sender as GridView;

                if (view.SelectedRowsCount < 2) return;

                GridHitInfo hi = view.CalcHitInfo(new Point(e.X, e.Y));

                if (e.Button == MouseButtons.Left && hi.RowHandle >= 0 &&
                    hi.InRowCell && hi.Column.Name == "colDelete")
                {
                    btnDelete_Click();
                }
            }
            catch (Exception)
            {
                return;
            }
        }

        private void repositoryItemButtonDelete_Click(object sender, EventArgs e)
        {
            btnDelete_Click();
        }

        private void repositoryItemButtonMigrate_Click(object sender, EventArgs e)
        {
            try
            {
                var order = orderRepository.GetById(Convert.ToInt32(
                    gridView1.GetFocusedRowCellValue("OrderId")));

                var frm = new frmIssueEditor();
                frm.Dt = CreateDataTable(order);
                frm.Customer = order.FullName;
                frm.IssueRepository = new Repository<Issue>(orderRepository.GetContext());
                frm.Text = "Thêm phiếu xuất";
                frm.ShowDialog();
            }
            catch (Exception ex)
            {
                Common.ShowErrorBox(ex.Message);
            }
        }

        DataTable dt;

        private DataTable CreateDataTable(Order order)
        {
            dt = new DataTable("IssueDetail");
            dt.BeginInit();
            dt.Columns.Add("Title");
            dt.Columns.Add("UnitPrice", System.Type.GetType("System.Decimal"));
            dt.Columns.Add("Quantity", System.Type.GetType("System.Int32"));
            dt.Columns.Add("Price", System.Type.GetType("System.Decimal"));
            dt.Columns.Add("IssueDetailId", System.Type.GetType("System.Int32"));
            dt.EndInit();

            InitDataTable(order);

            return dt;
        }

        private void InitDataTable(Order order)
        {
            try
            {
                foreach (var item in order.OrderDetails)
                {
                    DataRow row = dt.NewRow();

                    row["Title"] = item.AlbumId;
                    row["UnitPrice"] = item.UnitPrice;
                    row["Quantity"] = item.Quantity;
                    row["Price"] = item.UnitPrice * item.Quantity;
                    //row["IssueDetailId"] = item.IssueDetailId;
                    dt.Rows.Add(row);
                }
                dt.AcceptChanges();
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void repositoryItemButtonReceipt_Click(object sender, EventArgs e)
        {
            try
            {
                var order = orderRepository.GetById(Convert.ToInt32(
                    gridView1.GetFocusedRowCellValue("OrderId")));

                var frm = new frmReceiptEditor();
                frm.Dt = CreateDataTable(order);
                //frm.Customer = order.Username;
                frm.ReceiptRepository = new Repository<Receipt>(orderRepository.GetContext());
                frm.Text = "Thêm phiếu nhập";
                frm.ShowDialog();
            }
            catch (Exception ex)
            {
                Common.ShowErrorBox(ex.Message);
            }
        }

    }
}